<template>
  <div>
    <el-echarts
      theme="macarons"
      ref="chartRef"
      @onInit="onInit"
      :height="500"
      :option="option"
    ></el-echarts>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { echartsXFormatter } from '@vimi/utils-tool'
import { getParams } from './reportMixins'

export default {
  components: {},
  props: {
    queryParams: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: {
        showLoading: () => {},
        hideLoading: () => {},
      },
      loading: false,
      option: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {
    queryParams: {
      handler: function () {
        this.getFirstData()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    onInit(chart) {
      this.chart = chart
    },
    async getCountData(queryParams, tableName = 'report_analysis_for_bank') {
      const params = {
        ...getParams({
          ...queryParams,
          isBIQuery: 1,
          clientId: this.clientId,
        }),
      }
      const res = await this.$api.getData(this.$serviceName, tableName, params)
      return res.data || []
    },
    getFirstData() {
      const params = {
        ...this.queryParams,
        groupFields: ['bank_type', 'bank_type_name'],
        groupFunc: `count(1),round(sum(warranty_amount)|2)`,
        fields: ['bank_type', 'bank_type_name'],
      }
      this.chart.showLoading()
      this.loading = true
      let data = {}
      Promise.all([
        this.getCountData({ ...params, busStatus: 0 }),
        this.getCountData({ ...params, busStatus: 1 }),
        this.getCountData({ ...params, busStatus: 2 }),
      ])
        .then(([inData, outData, newData]) => {
          data = this.getOptionData(inData, outData, newData)
        })
        .finally(() => {
          const options = this.getOptions(data)
          this.setOption(options)
          this.loading = false
          this.chart.hideLoading()
        })
    },
    getOptionData(inData, outData, newData) {
      const data = {}
      inData.forEach(item => {
        data[item.bank_type] = {
          bankName: item.bank_type_name,
          inCount: item.p,
          inFunds: item.p1,
        }
      })
      outData.forEach(item => {
        data[item.bank_type] = {
          ...(data[item.bank_type] || {}),
          bankName: item.bank_type_name,
          outCount: item.p,
          outFunds: item.p1,
        }
      })
      newData.forEach(item => {
        data[item.bank_type] = {
          ...(data[item.bank_type] || {}),
          bankName: item.bank_type_name,
          newCount: item.p,
          newFunds: item.p1,
        }
      })
      return data
    },
    getOptions(data) {
      const options = {
        xData: [],
        aData: [], // 在保项目数
        bData: [], // 在保金额
        cData: [], // 解保项目数
        dData: [], // 解保金额
        eData: [], // 新增项目数
        fData: [], // 新增金额
      }
      Object.keys(data).forEach(type => {
        options.xData.push(
          (data[type].bankName || '').replace(
            /(股份有限公司|股份有限责任公司|有限责任公司|有限公司)$/,
            ''
          )
        )
        options.aData.push(data[type].inCount)
        options.bData.push(data[type].inFunds)
        options.cData.push(data[type].outCount)
        options.dData.push(data[type].outFunds)
        options.eData.push(data[type].newCount)
        options.fData.push(data[type].newFunds)
      })
      return options
    },
    setOption(data) {
      this.option = {
        title: {
          text: '',
          subtext: '',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false,
          },
        },
        axisPointer: {
          link: { xAxisIndex: 'all' },
        },
        legend: {
          data: ['在保项目', '解保项目', '新增项目', '在保金额', '解保金额', '新增金额'],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: [
          {
            left: 70,
            right: 50,
            top: 80,
            height: '32%',
          },
          {
            left: 70,
            right: 50,
            top: '55%',
            height: '32%',
          },
        ],
        dataZoom: [
          {
            show: true,
            realtime: true,
            xAxisIndex: [0, 1],
            zoomOnMouseWheel: false,
            moveOnMouseWheel: false,
          },
          {
            type: 'inside',
            realtime: true,
            xAxisIndex: [0, 1],
            zoomOnMouseWheel: false,
            moveOnMouseWheel: false,
          },
        ],
        xAxis: [
          {
            type: 'category',
            data: data.xData,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 4),
            },
          },
          {
            gridIndex: 1,
            type: 'category',
            data: data.xData,
            position: 'top',
            axisLabel: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '项目数(个)',
          },
          {
            type: 'value',
            name: '金额（万元）',
            gridIndex: 1,
            inverse: true,
          },
        ],
        series: [
          {
            name: '在保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.aData,
            barMaxWidth: 60,
            label: { show: true, position: 'top' },
          },
          {
            name: '解保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.cData,
            barMaxWidth: 60,
            label: { show: true, position: 'top' },
          },
          {
            name: '新增项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.eData,
            barMaxWidth: 60,
            label: { show: true, position: 'top' },
          },
          {
            name: '在保金额',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.bData,
            barMaxWidth: 60,
            label: { show: true, position: 'bottom' },
          },
          {
            name: '解保金额',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.dData,
            barMaxWidth: 60,
            label: { show: true, position: 'bottom' },
          },
          {
            name: '新增金额',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.fData,
            barMaxWidth: 60,
            label: { show: true, position: 'bottom' },
          },
        ],
      }
    },
    resize() {
      this.$nextTick(() => {
        const { chartRef } = this.$refs
        chartRef && chartRef.resize()
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
